<template>
  <div class="client-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><Monitor /></el-icon>
            客户端列表
          </span>
          <div class="card-actions">
            <el-button type="primary" size="small" @click="refreshClients">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button type="success" size="small" @click="showAddClientDialog">
              <el-icon><Plus /></el-icon>
              添加客户端
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-select
              v-model="filterForm.department"
              placeholder="选择部门"
              clearable
              style="width: 100%"
              @change="handleFilterChange"
            >
              <el-option label="全部部门" value="" />
              <el-option
                v-for="dept in departments"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="filterForm.status"
              placeholder="选择状态"
              clearable
              style="width: 100%"
              @change="handleFilterChange"
            >
              <el-option label="全部状态" value="" />
              <el-option label="在线" value="online" />
              <el-option label="离线" value="offline" />
              <el-option label="告警" value="warning" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="filterForm.keyword"
              placeholder="搜索客户端名称或IP"
              clearable
              @input="handleFilterChange"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleFilterChange">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 客户端表格 -->
      <el-table
        :data="clientsList"
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="客户端ID" width="120" align="center" header-align="center">
          <template #default="{ row }">
            <el-text class="client-id">{{ row.id }}</el-text>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="名称" min-width="140" align="left" header-align="center">
          <template #default="{ row }">
            <div class="client-name-cell">
              <el-text class="client-name">{{ row.name }}</el-text>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="user" label="用户" width="100" align="center" header-align="center">
          <template #default="{ row }">
            <el-text size="small" class="client-user">{{ row.user || '-' }}</el-text>
          </template>
        </el-table-column>

        <el-table-column prop="department" label="部门" width="100" align="center" header-align="center">
          <template #default="{ row }">
            <el-text size="small" class="client-dept">{{ row.department || '-' }}</el-text>
          </template>
        </el-table-column>



        <el-table-column prop="status" label="在线状态" width="100" align="center" header-align="center">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'online' ? 'success' : 'danger'"
              size="small"
            >
              <el-icon>
                <CircleCheck v-if="row.status === 'online'" />
                <CircleClose v-else />
              </el-icon>
              {{ row.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="ip" label="IP地址" width="130" align="center" header-align="center">
          <template #default="{ row }">
            <el-text class="client-ip">{{ row.ip }}</el-text>
          </template>
        </el-table-column>

        <el-table-column prop="lastHeartbeat" label="最后心跳" width="150" align="center" header-align="center">
          <template #default="{ row }">
            <el-text size="small">{{ formatDateTime(row.lastHeartbeat || row.last_heartbeat) }}</el-text>
          </template>
        </el-table-column>

        <el-table-column prop="configName" label="当前配置" width="120" align="center" header-align="center">
          <template #default="{ row }">
            <el-text size="small" class="config-name">{{ row.config_name || row.configName || '-' }}</el-text>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="configureClient(row)"
              >
                <el-icon><Setting /></el-icon>
                配置
              </el-button>

              <!-- 配置选择下拉框 -->
              <el-select
                v-model="selectedConfigs[row.id]"
                placeholder="选择配置"
                size="small"
                style="width: 120px; margin: 0 4px;"
                @change="(configId) => handleConfigSelection(row, configId)"
                clearable
              >
                <el-option
                  v-for="config in availableConfigs"
                  :key="config.id"
                  :label="config.name"
                  :value="config.id"
                >
                  <span style="float: left">{{ config.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">
                    {{ getConfigTypeText(config.type) }}
                  </span>
                </el-option>
              </el-select>

              <el-dropdown @command="(command) => handleClientAction(command, row)">
                <el-button size="small" link>
                  <el-icon><More /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item command="delete" divided>
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty
        v-if="clientsList.length === 0 && !loading"
        description="暂无客户端数据"
        :image-size="100"
      />
    </el-card>



    <!-- 添加/编辑客户端对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogMode === 'add' ? '添加客户端' : '编辑客户端'"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item v-if="dialogMode === 'edit'" label="客户端ID" prop="id">
          <el-input
            v-model="form.id"
            disabled
            placeholder="客户端ID"
          />
        </el-form-item>

        <el-form-item label="客户端名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入客户端名称"
          />
        </el-form-item>

        <el-form-item label="用户" prop="user">
          <el-input
            v-model="form.user"
            :disabled="dialogMode === 'edit'"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="部门" prop="dept">
          <el-select
            v-model="form.dept"
            :disabled="dialogMode === 'edit'"
            placeholder="请选择部门"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="IP地址" prop="ip">
          <el-input
            v-model="form.ip"
            placeholder="请输入IP地址"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          {{ dialogMode === 'add' ? '添加' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useClientsStore } from '@/stores/clients'
import { useWebSocketStore } from '@/stores/websocket'
import {
  Monitor, Refresh, Plus, CircleCheck, CircleClose,
  FullScreen, More, Edit, Delete, Download, Setting,
  Search, RefreshLeft
} from '@element-plus/icons-vue'
import { clientsService, departmentsService, configService } from '@/services/dataService.js'

const router = useRouter()
const clientsStore = useClientsStore()
const wsStore = useWebSocketStore()

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref('add') // 'add' | 'edit'
const submitting = ref(false)
const formRef = ref()



// 筛选相关
const filterForm = reactive({
  dept: '',
  status: '',
  keyword: ''
})

// 部门数据
const departments = ref([])

// 配置相关数据
const availableConfigs = ref([])
const selectedConfigs = ref({}) // 存储每个客户端选择的配置ID
const applyingConfig = ref(false)

// 表单数据
const form = reactive({
  id: '',
  name: '',
  user: '',
  dept: '',
  ip: ''
})

// 表单验证规则 - 根据对话框模式动态生成
const formRules = computed(() => {
  const rules = {
    name: [
      { required: true, message: '请输入客户端名称', trigger: 'blur' },
      { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    user: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    dept: [
      { required: true, message: '请选择部门', trigger: 'change' }
    ],
    ip: [
      { required: true, message: '请输入IP地址', trigger: 'blur' },
      { pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, message: '请输入有效的IP地址', trigger: 'blur' }
    ]
  }

  // 编辑模式下添加客户端ID验证
  if (dialogMode.value === 'edit') {
    rules.id = [
      { required: true, message: '客户端ID不能为空', trigger: 'blur' }
    ]
  }

  return rules
})

// 响应式数据
const clients = ref([])

// 计算属性 - 直接返回从API获取的客户端列表
const clientsList = computed(() => {
  return clients.value
})

// 方法
const loadDepartments = async () => {
  try {
    const response = await departmentsService.getDepartmentOptions()
    // 兼容两种API响应格式
    if (response.success || response.code === 200) {
      let departmentsData = []

      if (response.data && Array.isArray(response.data)) {
        // 真实API格式: {code: 200, data: [...]}
        departmentsData = response.data
      } else if (response.success && response.data) {
        // 虚拟数据格式: {success: true, data: [...]}
        departmentsData = response.data
      }

      departments.value = departmentsData || []
    } else {
      departments.value = []
    }
  } catch (error) {
    ElMessage.error('加载部门列表失败: ' + (error.message || '网络错误'))
    departments.value = []
  }
}

// 加载配置列表
const loadConfigs = async () => {
  try {
    const response = await configService.getConfigs()
    
    // 处理不同的API响应格式
    if (response && response.success !== false) {
      let configList = []

      // 真实API格式: {code: 200, data: {...}, message: 'Success'}
      if (response.code === 200 && response.data) {
        if (Array.isArray(response.data)) {
          configList = response.data
        } else if (response.data.list) {
          configList = response.data.list
        } else if (response.data.configs) {
          configList = response.data.configs
        }
      } else if (response.data && response.data.list) {
        // 虚拟数据格式: {success: true, data: {list: [...], total: n}}
        configList = response.data.list
      } else if (response.list) {
        // 虚拟数据格式: {success: true, list: [...], total: n}
        configList = response.list
      } else if (Array.isArray(response.data)) {
        // 直接返回数组格式: {success: true, data: [...]}
        configList = response.data
      } else if (Array.isArray(response)) {
        // 直接返回数组
        configList = response
      }

      // 确保每个配置项都有必要的字段
      availableConfigs.value = configList.map(config => ({
        ...config,
        targetId: config.targetId || config.target_id,
        updatedAt: config.updatedAt || config.updated_at,
        enabled: config.enabled !== undefined ? config.enabled : true,
        settings: config.settings || {}
      }))

    } else {
      availableConfigs.value = []
    }
  } catch (error) {
    console.error('加载配置列表失败:', error)
    ElMessage.error('加载配置列表失败: ' + (error.message || '网络错误'))
    availableConfigs.value = []
  }
}

const loadClients = async () => {
  try {
    loading.value = true

    const response = await clientsService.getClients()

    // 兼容两种API响应格式
    if (response.success || response.code === 200) {
      let clientsData = []

      if (response.data && response.data.list) {
        // 真实API格式: {code: 200, data: {list: [...]}}
        clientsData = response.data.list
      } else if (response.data && Array.isArray(response.data)) {
        // 备用格式: {code: 200, data: [...]}
        clientsData = response.data
      } else if (response.success && response.data) {
        // 虚拟数据格式: {success: true, data: {list: [...]}}
        clientsData = response.data.list || response.data
      }

      clients.value = clientsData || []
    } else {
      clients.value = []
    }
  } catch (error) {
    console.error('加载客户端列表失败:', error)
    ElMessage.error('加载客户端列表失败: ' + (error.message || '网络错误'))
    clients.value = []
  } finally {
    loading.value = false
  }
}

const refreshClients = async () => {
  await loadClients()
  ElMessage.success('客户端列表已刷新')
}

const isScreenSharingActive = (clientId) => {
  return clientsStore.isScreenSharingActive(clientId)
}

const toggleScreenSharing = (clientId, active) => {
  if (active) {
    wsStore.sendControlCommand(clientId, { action: 'start_screen_sharing' })
    clientsStore.startScreenSharing(clientId)
    ElMessage.success('已启动屏幕共享')
  } else {
    wsStore.sendControlCommand(clientId, { action: 'stop_screen_sharing' })
    clientsStore.stopScreenSharing(clientId)
    ElMessage.success('已停止屏幕共享')
  }
}

const saveRecording = (clientId) => {
  wsStore.sendControlCommand(clientId, {
    action: 'save_recording'
  })
  ElMessage.success('录屏保存请求已发送')
}

const controlClient = (clientId) => {
  // 跳转到屏幕共享页面并自动启动该客户端的屏幕共享，同时自动进入全屏
  router.push({
    name: 'ScreenSharing',
    query: {
      autoStart: clientId,
      autoFullscreen: 'true' // 自动全屏
    }
  })
}



// 筛选变化处理
const handleFilterChange = async () => {
  try {
    loading.value = true
    // 重新加载客户端数据，传递筛选参数
    const params = {}
    if (filterForm.status) params.status = filterForm.status
    if (filterForm.department) params.department = filterForm.department
    if (filterForm.keyword) params.keyword = filterForm.keyword

    const response = await clientsService.getClients(params)

    // 处理API响应
    if (response && response.success !== false) {
      let clientsData = []

      if (response.data && response.data.list) {
        // 真实API格式: {code: 200, data: {list: [...], total: n}}
        clientsData = response.data.list
      } else if (response.data && Array.isArray(response.data)) {
        // 备用格式: {code: 200, data: [...]}
        clientsData = response.data
      } else if (response.success && response.data) {
        // 虚拟数据格式: {success: true, data: {list: [...]}}
        clientsData = response.data.list || response.data
      } else if (Array.isArray(response)) {
        // 直接返回数组
        clientsData = response
      }

      clients.value = clientsData || []

      // 根据筛选结果显示不同的消息
      if (clients.value.length > 0) {
        ElMessage.success(`查询成功，找到 ${clients.value.length} 个客户端`)
      } else {
        ElMessage.info('未找到符合条件的客户端')
      }
    } else {
      clients.value = []
      ElMessage.warning('查询失败，请检查筛选条件')
    }
  } catch (error) {
    console.error('查询客户端失败:', error)
    ElMessage.error('查询客户端失败: ' + (error.message || '网络错误'))
    clients.value = []
  } finally {
    loading.value = false
  }
}

// 配置客户端
const configureClient = (client) => {
  // 跳转到客户端配置页面，并传递客户端ID
  router.push({
    path: '/client/config',
    query: { clientId: client.id }
  })
}

// 处理配置选择
const handleConfigSelection = async (client, configId) => {
  if (!configId) {
    // 清空选择
    return
  }

  try {
    // 找到选择的配置
    const selectedConfig = availableConfigs.value.find(config => config.id === configId)
    if (!selectedConfig) {
      ElMessage.error('选择的配置不存在')
      return
    }

    // 确认应用配置
    await ElMessageBox.confirm(
      `确定要将配置"${selectedConfig.name}"应用到客户端"${client.name}"吗？`,
      '确认应用配置',
      {
        confirmButtonText: '确定应用',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    applyingConfig.value = true

    // 构建应用配置的数据
    const applyData = {
      scope: 'individual',
      target_id: client.id,
      config_id: configId,
      client_ids: [client.id],
      applied_at: new Date().toISOString(),
      client_info: {
        id: client.id,
        name: client.name,
        ip: client.ip,
        status: client.status
      }
    }

    // 调用API应用配置
    const response = await configService.applyConfig(configId, applyData)

    // 显示成功消息
    if (response.failed && response.failed > 0) {
      ElMessage.warning(`配置"${selectedConfig.name}"已应用到客户端"${client.name}"，但部分操作失败`)
    } else {
      ElMessage.success(`配置"${selectedConfig.name}"已成功应用到客户端"${client.name}"`)
    }

    // 清空选择
    selectedConfigs.value[client.id] = null

  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      console.error('应用配置失败:', error)
      ElMessage.error('应用配置失败: ' + (error.message || '网络错误'))
    }
    // 清空选择
    selectedConfigs.value[client.id] = null
  } finally {
    applyingConfig.value = false
  }
}

// 获取配置类型文本
const getConfigTypeText = (type) => {
  const typeMap = {
    global: '全局',
    department: '部门',
    individual: '个人'
  }
  return typeMap[type] || type
}

// 获取部门名称
const getDepartmentName = (departmentId) => {
  if (!departmentId) return '-'
  const dept = departments.value.find(d => d.id === departmentId)
  return dept ? dept.name : '未分配'
}

// 格式化时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  try {
    const date = new Date(dateTimeStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return dateTimeStr
  }
}



// 重置筛选
const resetFilter = async () => {
  filterForm.department = ''
  filterForm.status = ''
  filterForm.keyword = ''
  // 重新加载所有客户端数据
  await loadClients()
  ElMessage.success('筛选条件已重置')
}

const handleClientAction = async (command, client) => {
  switch (command) {
    case 'edit':
      editClient(client)
      break
    case 'delete':
      await deleteClient(client)
      break
  }
}

const showAddClientDialog = () => {
  dialogMode.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const editClient = (client) => {
  dialogMode.value = 'edit'
  form.id = client.id
  form.name = client.name
  form.user = client.user || ''
  form.department = client.department || ''
  form.ip = client.ip || ''
  dialogVisible.value = true
}

const deleteClient = async (client) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除客户端 "${client.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用删除客户端API
    const response = await clientsService.deleteClient(client.id)

    if (response.success || response.code === 200) {
      ElMessage.success('客户端已删除')
      // 刷新列表
      await loadClients()
    } else {
      throw new Error(response.message || '删除失败')
    }
  } catch (error) {
    if (error.message && error.message !== 'cancel') {
      console.error('删除客户端失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
    // 用户取消删除时不显示错误
  }
}

const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    if (dialogMode.value === 'add') {



      // 调用添加客户端API
      const response = await clientsService.addClient({
        id: form.id,
        name: form.name,
        user: form.user,
        dept: form.dept,
        ip: form.ip
      })

      if (response.success || response.code === 200) {
        ElMessage.success('客户端添加成功')
      } else {
        throw new Error(response.message || '添加失败')
      }
    } else {
      // 调用更新客户端API（编辑模式下用户和部门不会被更新）
      const response = await clientsService.updateClient(form.id, {
        name: form.name,
        ip: form.ip
      })

      if (response.success || response.code === 200) {
        ElMessage.success('客户端更新成功')
      } else {
        throw new Error(response.message || '更新失败')
      }
    }

    dialogVisible.value = false
    // 刷新列表
    await loadClients()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = ''
  form.name = ''
  form.user = ''
  form.department = ''
  form.ip = ''
}

// 初始化
onMounted(async () => {
  await Promise.all([
    loadClients(),
    loadDepartments(),
    loadConfigs()
  ])
})
</script>

<style scoped>
.client-management {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.filter-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.client-details {
  max-height: 500px;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.client-id {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #606266;
}

.client-name-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.client-name {
  font-weight: 500;
}

.client-desc {
  color: #909399;
}

.client-ip {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
}

.screen-sharing-cell {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .action-buttons {
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    gap: 4px;
  }
}
</style>
